package com.registration.service;

import com.registration.bean.OrderBean;
import com.registration.bean.ScheduleBean;
import com.registration.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService{
@Autowired
private OrderMapper orderMapper;

@Autowired
private ScheduleService scheduleService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBean createRegistrationOrder(OrderBean order) {
        if (order.getTime_slot() == null) {
            throw new IllegalArgumentException("就诊时间段不能为空");
        }

        // 生成订单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStr = sdf.format(new Date());
        int seq = orderMapper.selectMaxOrderSeq();
        String orderNo = "REG" + timeStr + String.format("%03d", seq + 1);
        order.setOrder_no(orderNo);

        // 校验并锁定号源
        ScheduleBean schedule = scheduleService.checkAndLockQuota(order.getSchedule_id());
        if (schedule == null) {
            throw new RuntimeException("号源不足或已停售");
        }

        // 检查排班信息中的时间段是否为空
        if (schedule.getTime_slot() == null) {
            throw new RuntimeException("排班信息不完整：就诊时间段为空");
        }

        // 设置就诊序号（visit_no）
        int remainingQuota = schedule.getRemaining_quota();
        String visitNo = generateVisitNo(schedule.getTime_slot(), remainingQuota);
        order.setVisit_no(visitNo);

        // 创建订单
        int rows = orderMapper.insertRegistrationOrder(order);
        if (rows <= 0) {
            throw new RuntimeException("订单创建失败");
        }

        // 确保获取到生成的ID
        if (order.getOrder_id() == null) {
            throw new RuntimeException("无法获取生成的订单ID");
        }

        // 减少号源
        rows = scheduleService.decreaseQuota(order.getSchedule_id());
        if (rows <= 0) {
            throw new RuntimeException("号源更新失败");
        }

        // 返回完整的订单对象
        return order;
    }



    private String generateVisitNo(Integer timeSlot, int remainingQuota) {
        String prefix;
        switch (timeSlot) {
            case 1: prefix = "A"; break; // 上午
            case 2: prefix = "P"; break; // 下午
            case 3: prefix = "E"; break; // 晚上
            default: prefix = "X";
        }
        return prefix + String.format("%02d", remainingQuota);
    }

    @Override
    public List<OrderBean> getOrdersByUserId(Integer userId, Integer orderStatus) {
        if (userId == null) {
            return Collections.emptyList();
        }
        return orderMapper.selectOrdersByUserId(userId, orderStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Integer orderId, Integer userId) {
        // 1. 校验订单是否存在且属于当前用户（简化逻辑，实际需查询订单表验证）
        OrderBean order = orderMapper.selectOrderById(orderId); // 需在Mapper中补充该方法
        if (order == null || !order.getUser_id().equals(userId)) {
            return false;
        }

        // 2. 校验订单状态（仅允许取消“待支付”或“已支付”未就诊订单）
        if (order.getOrder_status() != 0 && order.getOrder_status() != 1) {
            return false;
        }

        // 3. 取消订单（更新状态）
        orderMapper.cancelOrder(orderId);

        // 4. 恢复号源
        scheduleService.increaseQuota(order.getSchedule_id());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rescheduleOrder(Integer orderId, Integer newScheduleId, Integer userId) {
        // 1. 查询原订单并验证权限
        OrderBean order = orderMapper.selectOrderById(orderId);
        if (order == null || !order.getUser_id().equals(userId)) {
            return false;
        }

        // 2. 校验新排班号源
        ScheduleBean newSchedule = scheduleService.checkAndLockQuota(newScheduleId);
        if (newSchedule == null) {
            throw new RuntimeException("新排班号源不足");
        }

        // 3. 恢复原排班号源
        scheduleService.increaseQuota(order.getSchedule_id());

        // 4. 更新订单至新排班
        Date newVisitDate = newSchedule.getVisit_date();
        Integer newTimeSlot = newSchedule.getTime_slot();
        orderMapper.updateScheduleInfo(orderId, newScheduleId, newVisitDate, newTimeSlot);

        // 5. 减少新排班号源
        scheduleService.decreaseQuota(newScheduleId);
        return true;
    }


    @Override
    public OrderBean selectOrderDetailById(Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return null;
        }
        OrderBean order = orderMapper.selectOrderDetailById(orderId);

        // 如果visit_no为空，设置默认值
        if (order != null && order.getQueue_number() == null) {
            order.setQueue_number(order.getVisit_no());
        }

        return order;
    }

    /**
     * 根据患者ID和订单状态查询挂号订单
     * @param patientId 患者ID
     * @param orderStatus 订单状态
     * @return 挂号订单列表
     */
    @Override
    public List<OrderBean> selectOrdersByPatientId(Integer patientId, Integer orderStatus) {
        if (patientId == null || patientId <= 0) {
            return Collections.emptyList();
        }
        return orderMapper.selectOrdersByPatientId(patientId, orderStatus);
    }



    /**
     * 根据患者ID查询挂号订单
     * @param patientId 患者ID
     * @return 挂号订单列表
     */
    @Override
    public List<OrderBean> selectOrdersByPatientId(Integer patientId) {
        if (patientId == null || patientId <= 0) {
            return Collections.emptyList();
        }
        return orderMapper.selectOrdersByPatientId(patientId,1);
    }

    @Override
    public OrderBean getOrderById(Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return null;
        }
        return orderMapper.selectOrderById(orderId);
    }

    @Override
    public List<OrderBean> selectVisitedOrders(Integer user_id) {
        return orderMapper.selectVisitedOrders(user_id);
    }

    /**
     * 修改订单的状态
     * @param orderId
     * @param order 订单信息
     * @return
     */
    @Override
    public int updateOrder(Integer orderId, OrderBean order) {
        return orderMapper.updateOrder(orderId, order);
    }


}
